﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ObjectSweptVolume.CObjectSweptVolumeViewModel
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnProcessSimulateCommands.SweptVolume;
using EngineeringInternalExtension;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using Tecnomatix.Engineering;


namespace DnProcessSimulateCommands.ObjectSweptVolume;

internal class CObjectSweptVolumeViewModel : INotifyPropertyChanged
{
  private const double DEFAULT_ACCURACY_MM = 60.0;
  private const double MAX_ACCURACY_MM = 100.0;
  private const double WARNING_ACCURACY_THRESHOLD_MM = 10.0;
  private const double DEFAULT_CLEARANCE_MM = 0.0;
  private const double MAX_CLEARANCE_MM = 5000.0;
  private const bool DEFAULT_INCLUDE_CABLES = true;
  private static readonly string RegistryPath = TxApplication.RegistryPath + "\\TUNE\\NewAssembler\\Commands Info\\DnProcessSimulateCommands\\Dialogs\\CObjectSweptVolumeDlg";
  private const string AccuracyKey = "Accuracy";
  private const string ClearanceKey = "Clearance";
  private const string IncludeCablesKey = "IncludeCables";
  private double m_accuracy = 60.0;
  private bool m_showAccuracyWarning;
  private string m_accuracyText = string.Empty;
  private double m_clearance;
  private bool m_isIncludedCables = true;
  private bool m_shouldCollectData = true;
  private bool m_hasCollectedData;
  private bool m_isSimulationRunning;
  private bool m_isCreationExecuting;
  private string m_createBtnText = string.Empty;
  private double m_progress;
  private ObservableCollection<CApObjectSweptVolumeItem> m_items = new ObservableCollection<CApObjectSweptVolumeItem>();
  private ObservableCollection<CApObjectSweptVolumeItem> m_selectedItems = new ObservableCollection<CApObjectSweptVolumeItem>();
  private Dictionary<ITxObject, CApObjectSweptVolumeSamplesCollector> m_observedObjs = new Dictionary<ITxObject, CApObjectSweptVolumeSamplesCollector>();
  private CApObjectSweptVolumeSimulationHandler m_simulationHandler;
  private CApObjectSweptVolumeCreator m_sweptVolumeCreator;
  private CApObjectSweptVolumeVMCommand m_addItemsCommand;
  private CApObjectSweptVolumeVMCommand m_removeItemsCommand;
  private CApObjectSweptVolumeVMCommand m_createCommand;

  public CObjectSweptVolumeViewModel()
  {
    this.LoadWindowData();
    this.OnAccuracyUpdated();
    this.UpdateCreateBtnText();
    this.InitializeSimulationHandler();
    this.RegisterForApplicationEvents();
    this.Items.CollectionChanged += new NotifyCollectionChangedEventHandler(this.Items_CollectionChanged);
  }

  public ObservableCollection<CApObjectSweptVolumeItem> Items
  {
    get => this.m_items;
    private set
    {
      if (this.m_items == value)
        return;
      this.m_items = value;
      this.OnPropertyChanged(nameof (Items));
    }
  }

  public ObservableCollection<CApObjectSweptVolumeItem> SelectedItems
  {
    get => this.m_selectedItems;
    set
    {
      if (this.m_selectedItems == value)
        return;
      this.m_selectedItems = value;
      this.OnPropertyChanged(nameof (SelectedItems));
      this.RemoveItemsCommand.RaiseCanExecuteChanged();
    }
  }

  public double SelectedAccuracy
  {
    get => this.m_accuracy;
    set
    {
      if (this.m_accuracy == value)
        return;
      this.m_accuracy = value;
      this.OnPropertyChanged(nameof (SelectedAccuracy));
      this.OnAccuracyUpdated();
    }
  }

  public bool ShowAccuracyWarning
  {
    get => this.m_showAccuracyWarning;
    set
    {
      if (this.m_showAccuracyWarning == value)
        return;
      this.m_showAccuracyWarning = value;
      this.OnPropertyChanged(nameof (ShowAccuracyWarning));
    }
  }

  public string AccuracyText
  {
    get => this.m_accuracyText;
    set
    {
      if (!(this.m_accuracyText != value))
        return;
      this.m_accuracyText = value;
      this.OnPropertyChanged(nameof (AccuracyText));
    }
  }

  public bool IsIncludedCables
  {
    get => this.m_isIncludedCables;
    set
    {
      if (this.m_isIncludedCables == value)
        return;
      this.m_isIncludedCables = value;
      this.OnPropertyChanged(nameof (IsIncludedCables));
      this.ClearCollectedData();
      this.UpdateSamplesCollectors_OnIsIncludeCablesChanged();
    }
  }

  public double SafetyClearance
  {
    get => this.m_clearance;
    set
    {
      if (this.m_clearance == value)
        return;
      this.m_clearance = value;
      this.OnPropertyChanged(nameof (SafetyClearance));
    }
  }

  public bool ShouldCollectData
  {
    get => this.m_shouldCollectData;
    set
    {
      if (this.m_shouldCollectData == value)
        return;
      this.m_shouldCollectData = value;
      this.OnPropertyChanged(nameof (ShouldCollectData));
      if (this.m_shouldCollectData)
        this.StartCollectingData();
      else
        this.StopCollectingData();
    }
  }

  public bool HasCollectedData
  {
    get => this.m_hasCollectedData;
    set
    {
      if (this.m_hasCollectedData == value)
        return;
      this.m_hasCollectedData = value;
      this.OnPropertyChanged(nameof (HasCollectedData));
      this.CreateCommand.RaiseCanExecuteChanged();
    }
  }

  public bool IsSimulationRunning
  {
    get => this.m_isSimulationRunning;
    set
    {
      if (this.m_isSimulationRunning == value)
        return;
      this.m_isSimulationRunning = value;
      this.OnPropertyChanged(nameof (IsSimulationRunning));
      this.CreateCommand.RaiseCanExecuteChanged();
      this.AddItemsCommand.RaiseCanExecuteChanged();
      this.RemoveItemsCommand.RaiseCanExecuteChanged();
    }
  }

  public bool IsCreationExecuting
  {
    get => this.m_isCreationExecuting;
    set
    {
      if (this.m_isCreationExecuting == value)
        return;
      this.m_isCreationExecuting = value;
      this.OnPropertyChanged(nameof (IsCreationExecuting));
      this.UpdateCreateBtnText();
      if (!this.m_isCreationExecuting)
        this.Progress = 0.0;
      this.CreateCommand.RaiseCanExecuteChanged();
    }
  }

  public string CreateBtnText
  {
    get => this.m_createBtnText;
    set
    {
      if (!(this.m_createBtnText != value))
        return;
      this.m_createBtnText = value;
      this.OnPropertyChanged(nameof (CreateBtnText));
    }
  }

  public double Progress
  {
    get => this.m_progress;
    set
    {
      if (this.m_progress == value)
        return;
      this.m_progress = value;
      this.OnPropertyChanged(nameof (Progress));
    }
  }

  public void Uninitialize()
  {
    this.ClearObservedObjects();
    this.UnRegisterForApplicationEvents();
    this.Items.CollectionChanged -= new NotifyCollectionChangedEventHandler(this.Items_CollectionChanged);
    this.UnInitializeSimulationHandler();
  }

  public void AddPreSelectedItems()
  {
    this.AddObjectItems(this.ExtractSupportedObjects_FromExternalSelection());
  }

  public void RemoveSelectedItems()
  {
    if (this.SelectedItems.Count <= 0)
      return;
    this.RemoveItems();
  }

  public void OnLinearUnitChanged() => this.UpdateAccuracyText();

  public void OnWindowClosed() => this.SaveWindowData();

  public void ForceAbortCreation()
  {
    if (this.m_sweptVolumeCreator == null)
      return;
    this.m_sweptVolumeCreator.ShouldAbort = true;
  }

  public event PropertyChangedEventHandler PropertyChanged;

  protected virtual void OnPropertyChanged(string propertyName)
  {
    if (this.PropertyChanged == null)
      return;
    this.PropertyChanged((object) this, new PropertyChangedEventArgs(propertyName));
  }

  public event CObjectSweptVolumeViewModel.ItemSelectionForcedEventHandler ItemSelectionForced;

  protected void OnItemSelectionForced(IEnumerable<int> rows)
  {
    if (this.ItemSelectionForced == null)
      return;
    this.ItemSelectionForced((object) this, new CObjectSweptVolumeViewModel.ItemSelectionForcedEventArgs(rows));
  }

  public CApObjectSweptVolumeVMCommand AddItemsCommand
  {
    get
    {
      return this.m_addItemsCommand ?? (this.m_addItemsCommand = new CApObjectSweptVolumeVMCommand((Action) (() => this.AddItems()), (Func<bool>) (() => this.CanAddItems())));
    }
  }

  private void AddItems()
  {
    TxObjectList externalSelection = this.ExtractSupportedObjects_FromExternalSelection();
    this.AddObjectItems(externalSelection);
    this.SelectedItems = new ObservableCollection<CApObjectSweptVolumeItem>();
    this.OnItemSelectionForced(this.GetItemIndices(externalSelection));
  }

  private bool CanAddItems()
  {
    return !this.IsSimulationRunning && ((Collection<ITxObject>) this.ExtractSupportedObjects_FromExternalSelection()).Count > 0;
  }

  public CApObjectSweptVolumeVMCommand RemoveItemsCommand
  {
    get
    {
      return this.m_removeItemsCommand ?? (this.m_removeItemsCommand = new CApObjectSweptVolumeVMCommand((Action) (() => this.RemoveItems()), (Func<bool>) (() => this.CanRemoveItems())));
    }
  }

  private void RemoveItems()
  {
    IEnumerable<int> itemIndices = this.GetItemIndices((IEnumerable<CApObjectSweptVolumeItem>) this.SelectedItems);
    this.RemoveObjectItems((IEnumerable<CApObjectSweptVolumeItem>) this.SelectedItems.ToList<CApObjectSweptVolumeItem>());
    this.SelectedItems = new ObservableCollection<CApObjectSweptVolumeItem>();
    int? nullable = new int?();
    foreach (int num in itemIndices)
    {
      if (!nullable.HasValue || num < nullable.Value)
        nullable = new int?(num);
    }
    if (nullable.HasValue && nullable.Value >= 1)
    {
      this.OnItemSelectionForced((IEnumerable<int>) new List<int>(1)
      {
        nullable.Value - 1
      });
    }
    else
    {
      if (this.m_items.Count <= 0)
        return;
      this.OnItemSelectionForced((IEnumerable<int>) new List<int>(1)
      {
        0
      });
    }
  }

  private bool CanRemoveItems()
  {
    return !this.IsSimulationRunning && this.SelectedItems.Count<CApObjectSweptVolumeItem>() > 0;
  }

  public CApObjectSweptVolumeVMCommand CreateCommand
  {
    get
    {
      return this.m_createCommand ?? (this.m_createCommand = new CApObjectSweptVolumeVMCommand((Action) (() => this.Create()), (Func<bool>) (() => this.CanCreate())));
    }
  }

  private void Create()
  {
    if (!this.IsCreationExecuting)
    {
      this.IsCreationExecuting = true;
      // ISSUE: method pointer
      this.m_sweptVolumeCreator = new CApObjectSweptVolumeCreator(this.GetAllSamplesCollectors(), this.SelectedAccuracy, this.SafetyClearance, true, new TxSweptVolume_MayProceedCalculation((object) this, __methodptr(MayProceedCalculation)));
      this.m_sweptVolumeCreator.BeforeCalculatingSweptVolumeEntity += new EventHandler(this.M_sweptVolumeCreator_BeforeCalculatingSweptVolumeEntity);
      this.m_sweptVolumeCreator.Execute();
      if (this.m_sweptVolumeCreator != null)
      {
        this.m_sweptVolumeCreator.BeforeCalculatingSweptVolumeEntity -= new EventHandler(this.M_sweptVolumeCreator_BeforeCalculatingSweptVolumeEntity);
        this.m_sweptVolumeCreator = (CApObjectSweptVolumeCreator) null;
      }
      this.IsCreationExecuting = false;
    }
    else
    {
      if (this.m_sweptVolumeCreator == null)
        return;
      this.m_sweptVolumeCreator.ShouldAbort = true;
    }
  }

  private void M_sweptVolumeCreator_BeforeCalculatingSweptVolumeEntity(object sender, EventArgs e)
  {
    this.Progress = 5.0;
    Application.DoEvents();
  }

  private bool CanCreate()
  {
    if (this.IsCreationExecuting)
      return true;
    return this.HasCollectedData && this.Items.Count > 0 && !this.IsSimulationRunning;
  }

  private void AddObjectItems(TxObjectList supportedObjs)
  {
    foreach (ITxObject supportedObj in (Collection<ITxObject>) supportedObjs)
      this.AddObjectItem(supportedObj);
  }

  private void AddObjectItem(ITxObject supportedObj)
  {
    if (this.FindItem(supportedObj) != null)
      return;
    CApObjectSweptVolumeItem objectSweptVolumeItem = new CApObjectSweptVolumeItem(supportedObj);
    this.AddObservedObject(supportedObj);
    this.m_items.Add(objectSweptVolumeItem);
  }

  private void RemoveObjectItem(ITxObject obj)
  {
    CApObjectSweptVolumeItem objectSweptVolumeItem = this.FindItem(obj);
    if (objectSweptVolumeItem == null)
      return;
    this.RemoveObservedObject(obj);
    this.m_items.Remove(objectSweptVolumeItem);
  }

  private void RemoveObjectItems(IEnumerable<CApObjectSweptVolumeItem> items)
  {
    foreach (CApObjectSweptVolumeItem objectSweptVolumeItem in items)
    {
      this.RemoveObservedObject(objectSweptVolumeItem.Object);
      this.m_items.Remove(objectSweptVolumeItem);
    }
  }

  private void ClearObjectItems()
  {
    this.ClearObservedObjects();
    this.m_items.Clear();
  }

  private CApObjectSweptVolumeItem FindItem(ITxObject obj)
  {
    return this.m_items.FirstOrDefault<CApObjectSweptVolumeItem>((Func<CApObjectSweptVolumeItem, bool>) (s => s.Object == obj));
  }

  private IEnumerable<int> GetItemIndices(IEnumerable<CApObjectSweptVolumeItem> items)
  {
    List<int> itemIndices = new List<int>();
    foreach (CApObjectSweptVolumeItem objectSweptVolumeItem in items)
    {
      int? itemIndex = this.GetItemIndex(objectSweptVolumeItem);
      if (itemIndex.HasValue)
        itemIndices.Add(itemIndex.Value);
    }
    return (IEnumerable<int>) itemIndices;
  }

  private int? GetItemIndex(CApObjectSweptVolumeItem item)
  {
    for (int index = 0; index < this.m_items.Count; ++index)
    {
      if (this.m_items[index] == item)
        return new int?(index);
    }
    return new int?();
  }

  private IEnumerable<int> GetItemIndices(TxObjectList objs)
  {
    List<int> itemIndices = new List<int>();
    foreach (ITxObject itxObject in (Collection<ITxObject>) objs)
    {
      int? itemIndex = this.GetItemIndex(itxObject);
      if (itemIndex.HasValue)
        itemIndices.Add(itemIndex.Value);
    }
    return (IEnumerable<int>) itemIndices;
  }

  private int? GetItemIndex(ITxObject obj)
  {
    for (int index = 0; index < this.m_items.Count; ++index)
    {
      if (this.m_items[index].Object == obj)
        return new int?(index);
    }
    return new int?();
  }

  private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  {
    this.ClearCollectedData();
    this.CreateCommand.RaiseCanExecuteChanged();
  }

  private TxObjectList ExtractSupportedObjects_FromExternalSelection()
  {
    TxObjectList externalSelection = new TxObjectList();
    foreach (ITxObject allItem in (Collection<ITxObject>) TxApplication.ActiveSelection.GetAllItems())
    {
      if (allItem is TxCompoundResource)
      {
        foreach (ITxComponent allDescendant in (Collection<ITxObject>) (allItem as TxCompoundResource).GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (ITxComponent))))
        {
          if (this.IsSupportedObject((ITxObject) allDescendant))
          {
            ITxComponent topLevelComponent = this.GetTopLevelComponent(allDescendant);
            if (!((Collection<ITxObject>) externalSelection).Contains((ITxObject) topLevelComponent))
              ((Collection<ITxObject>) externalSelection).Add((ITxObject) topLevelComponent);
          }
        }
      }
      else if (allItem is TxCompoundPart)
      {
        foreach (ITxComponent allDescendant in (Collection<ITxObject>) (allItem as TxCompoundPart).GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (ITxComponent))))
        {
          if (this.IsSupportedObject((ITxObject) allDescendant) && !((Collection<ITxObject>) externalSelection).Contains((ITxObject) allDescendant))
            ((Collection<ITxObject>) externalSelection).Add((ITxObject) allDescendant);
        }
      }
      else if (this.IsSupportedObject(allItem) && !((Collection<ITxObject>) externalSelection).Contains(allItem))
        ((Collection<ITxObject>) externalSelection).Add(allItem);
    }
    return externalSelection;
  }

  private ITxComponent GetTopLevelComponent(ITxComponent comp)
  {
    ITxComponent topLevelComponent = comp;
    for (ITxObjectCollection collection = ((ITxObject) comp).Collection; collection != null && collection is ITxComponent; collection = ((ITxObject) collection).Collection)
      topLevelComponent = collection as ITxComponent;
    return topLevelComponent;
  }

  private bool IsSupportedObject(ITxObject obj)
  {
    return obj is ITxComponent && !(obj is TxSweptVolume) && !(obj is TxInterferenceVolume) || obj is ITxPartAppearance || obj is ITxSafetyObject || obj is ITxCable;
  }

  private bool IsStandardModeAppearance(ITxObject obj)
  {
    return obj is ITxPartAppearance && TxEngineeringDataInternal.GlobalGetPartsMode() != 2;
  }

  private void AddObservedObject(ITxObject obj)
  {
    if (this.m_observedObjs.ContainsKey(obj))
      return;
    this.RegisterForEvents(obj);
    CApObjectSweptVolumeSamplesCollector samplesCollector = this.CreateAndInitSamplesCollector(obj);
    this.m_observedObjs.Add(obj, samplesCollector);
  }

  private void RemoveObservedObject(ITxObject obj)
  {
    if (!this.m_observedObjs.ContainsKey(obj))
      return;
    this.UnRegisterForEvents(obj);
    CApObjectSweptVolumeSamplesCollector observedObj = this.m_observedObjs[obj];
    if (observedObj != null)
      this.UnitializeSamplesCollector(observedObj);
    this.m_observedObjs.Remove(obj);
  }

  private void ClearObservedObjects()
  {
    Dictionary<ITxObject, CApObjectSweptVolumeSamplesCollector>.Enumerator enumerator = this.m_observedObjs.GetEnumerator();
    while (enumerator.MoveNext())
    {
      KeyValuePair<ITxObject, CApObjectSweptVolumeSamplesCollector> current = enumerator.Current;
      this.UnRegisterForEvents(current.Key);
      current = enumerator.Current;
      CApObjectSweptVolumeSamplesCollector samplesCollector = current.Value;
      if (samplesCollector != null)
        this.UnitializeSamplesCollector(samplesCollector);
    }
    this.m_observedObjs.Clear();
  }

  private void RegisterForEvents(ITxObject obj)
  {
    obj.Deleted += new TxObject_DeletedEventHandler(this.Obj_Deleted);
    obj.NameChanged += new TxObject_NameChangedEventHandler(this.Obj_NameChanged);
  }

  private void UnRegisterForEvents(ITxObject obj)
  {
    obj.Deleted -= new TxObject_DeletedEventHandler(this.Obj_Deleted);
    obj.NameChanged -= new TxObject_NameChangedEventHandler(this.Obj_NameChanged);
  }

  private void CreateAndInitMissingSamplesCollectors()
  {
    foreach (ITxObject key in this.m_observedObjs.Keys.ToList<ITxObject>())
    {
      if (this.m_observedObjs[key] == null)
      {
        CApObjectSweptVolumeSamplesCollector samplesCollector = this.CreateAndInitSamplesCollector(key);
        this.m_observedObjs[key] = samplesCollector;
      }
    }
  }

  private CApObjectSweptVolumeSamplesCollector CreateAndInitSamplesCollector(ITxObject obj)
  {
    if (this.m_simulationHandler == null)
      return (CApObjectSweptVolumeSamplesCollector) null;
    CApObjectSweptVolumeSamplesCollector samplesCollector = new CApObjectSweptVolumeSamplesCollector(this.m_simulationHandler, new CApSVSamplingObjectsHandler(obj, this.IsIncludedCables));
    samplesCollector.Initialize();
    this.RegisterForSamplesCollectorEvents(samplesCollector);
    return samplesCollector;
  }

  private void UnitializeSamplesCollector(
    CApObjectSweptVolumeSamplesCollector samplesCollector)
  {
    if (samplesCollector == null)
      return;
    samplesCollector.UnInitialize();
    this.UnRegisterForSamplesCollectorEvents(samplesCollector);
  }

  private void RegisterForSamplesCollectorEvents(
    CApObjectSweptVolumeSamplesCollector samplesCollector)
  {
    samplesCollector.FirstSampleAdded += new EventHandler(this.SamplesCollector_FirstSampleAdded);
  }

  private void UnRegisterForSamplesCollectorEvents(
    CApObjectSweptVolumeSamplesCollector samplesCollector)
  {
    samplesCollector.FirstSampleAdded -= new EventHandler(this.SamplesCollector_FirstSampleAdded);
  }

  private void SamplesCollector_FirstSampleAdded(object sender, EventArgs e)
  {
    this.HasCollectedData = true;
  }

  private IEnumerable<CApObjectSweptVolumeSamplesCollector> GetAllSamplesCollectors()
  {
    List<CApObjectSweptVolumeSamplesCollector> samplesCollectors = new List<CApObjectSweptVolumeSamplesCollector>();
    foreach (CApObjectSweptVolumeSamplesCollector samplesCollector in this.m_observedObjs.Values)
    {
      if (samplesCollector != null)
        samplesCollectors.Add(samplesCollector);
    }
    return (IEnumerable<CApObjectSweptVolumeSamplesCollector>) samplesCollectors;
  }

  private void UpdateSamplesCollectors_OnIsIncludeCablesChanged()
  {
    foreach (CApObjectSweptVolumeSamplesCollector samplesCollector in this.GetAllSamplesCollectors())
      samplesCollector.IncludeCables = this.IsIncludedCables;
  }

  private void UpdateSamplesCollectors_OnCollectingDataChanged()
  {
    foreach (CApObjectSweptVolumeSamplesCollector samplesCollector in this.GetAllSamplesCollectors())
      samplesCollector.CanCollectSamples = this.ShouldCollectData;
  }

  private void UpdateSamplesCollectors_ClearData()
  {
    foreach (CApObjectSweptVolumeSamplesCollector samplesCollector in this.GetAllSamplesCollectors())
      samplesCollector.ClearData();
  }

  private bool SamplesCollectors_ContainsData()
  {
    foreach (CApObjectSweptVolumeSamplesCollector samplesCollector in this.GetAllSamplesCollectors())
    {
      if (samplesCollector.ContainsData)
        return true;
    }
    return false;
  }

  private void OnAccuracyUpdated()
  {
    this.UpdateAccuracyWarning();
    this.UpdateAccuracyText();
  }

  private void UpdateAccuracyWarning() => this.ShowAccuracyWarning = this.SelectedAccuracy < 10.0;

  private void UpdateAccuracyText()
  {
    this.AccuracyText = Math.Round(this.SelectedAccuracy / TxApplication.Options.Units.LinearMultiplier, Math.Min(TxApplication.Options.Units.LinearDigitsAfterDecimalPoint, 2)).ToString();
  }

  private void UpdateCreateBtnText()
  {
    this.CreateBtnText = this.IsCreationExecuting ? StringTable.OSV_DLG_BTN_STOP : StringTable.OSV_DLG_BTN_CREATE;
  }

  private void RegisterForApplicationEvents()
  {
    TxApplication.ActiveSelection.ItemsAdded += new TxSelection_ItemsAddedEventHandler(this.ActiveSelection_ItemsAdded);
    TxApplication.ActiveSelection.ItemsRemoved += new TxSelection_ItemsRemovedEventHandler(this.ActiveSelection_ItemsRemoved);
    TxApplication.ActiveSelection.ItemsSet += new TxSelection_ItemsSetEventHandler(this.ActiveSelection_ItemsSet);
    TxApplication.ActiveSelection.Cleared += new TxSelection_ClearedEventHandler(this.ActiveSelection_Cleared);
  }

  private void UnRegisterForApplicationEvents()
  {
    TxApplication.ActiveSelection.ItemsAdded -= new TxSelection_ItemsAddedEventHandler(this.ActiveSelection_ItemsAdded);
    TxApplication.ActiveSelection.ItemsRemoved -= new TxSelection_ItemsRemovedEventHandler(this.ActiveSelection_ItemsRemoved);
    TxApplication.ActiveSelection.ItemsSet -= new TxSelection_ItemsSetEventHandler(this.ActiveSelection_ItemsSet);
    TxApplication.ActiveSelection.Cleared -= new TxSelection_ClearedEventHandler(this.ActiveSelection_Cleared);
  }

  private void ActiveSelection_ItemsRemoved(object sender, TxSelection_ItemsRemovedEventArgs args)
  {
    this.OnExternalSelectionChanged();
  }

  private void ActiveSelection_ItemsAdded(object sender, TxSelection_ItemsAddedEventArgs args)
  {
    this.OnExternalSelectionChanged();
  }

  private void ActiveSelection_ItemsSet(object sender, TxSelection_ItemsSetEventArgs args)
  {
    this.OnExternalSelectionChanged();
  }

  private void ActiveSelection_Cleared(object sender, TxSelection_ClearedEventArgs args)
  {
    this.OnExternalSelectionChanged();
  }

  private void OnExternalSelectionChanged() => this.AddItemsCommand.RaiseCanExecuteChanged();

  private void Obj_Deleted(object sender, TxObject_DeletedEventArgs args)
  {
    this.RemoveObjectItem(sender as ITxObject);
    this.RemoveItemsCommand.RaiseCanExecuteChanged();
  }

  private void Obj_NameChanged(object sender, TxObject_NameChangedEventArgs args)
  {
    this.FindItem(sender as ITxObject)?.UpdateName();
  }

  private void LoadWindowData()
  {
    double num1 = CApObjectSweptVolumeDialogPersistency.TryGetValueFromRegistry<double>(CObjectSweptVolumeViewModel.RegistryPath, "Accuracy", 60.0);
    if (num1 < 0.0)
      num1 = 0.0;
    else if (num1 > 100.0)
      num1 = 100.0;
    this.SelectedAccuracy = num1;
    double num2 = CApObjectSweptVolumeDialogPersistency.TryGetValueFromRegistry<double>(CObjectSweptVolumeViewModel.RegistryPath, "Clearance", 0.0);
    if (num2 < 0.0)
      num2 = 0.0;
    else if (num2 > 5000.0)
      num2 = 5000.0;
    this.SafetyClearance = num2;
    this.IsIncludedCables = CApObjectSweptVolumeDialogPersistency.TryGetValueFromRegistry<bool>(CObjectSweptVolumeViewModel.RegistryPath, "IncludeCables", true);
  }

  private void SaveWindowData()
  {
    CApObjectSweptVolumeDialogPersistency.SaveValueToRegistry(CObjectSweptVolumeViewModel.RegistryPath, "Accuracy", this.SelectedAccuracy.ToString());
    CApObjectSweptVolumeDialogPersistency.SaveValueToRegistry(CObjectSweptVolumeViewModel.RegistryPath, "Clearance", this.SafetyClearance.ToString());
    CApObjectSweptVolumeDialogPersistency.SaveValueToRegistry(CObjectSweptVolumeViewModel.RegistryPath, "IncludeCables", this.IsIncludedCables.ToString());
  }

  private void StartCollectingData() => this.UpdateSamplesCollectors_OnCollectingDataChanged();

  private void StopCollectingData() => this.UpdateSamplesCollectors_OnCollectingDataChanged();

  private void ClearCollectedData()
  {
    this.UpdateSamplesCollectors_ClearData();
    this.HasCollectedData = false;
  }

  private void InitializeSimulationHandler()
  {
    if (this.m_simulationHandler != null)
      return;
    this.m_simulationHandler = new CApObjectSweptVolumeSimulationHandler();
    this.m_simulationHandler.Initialize();
    this.IsSimulationRunning = this.m_simulationHandler.IsSimulationStarted;
    this.RegisterForSimulationHandlerEvents();
    if (this.m_observedObjs.Count <= 0)
      return;
    this.CreateAndInitMissingSamplesCollectors();
  }

  private void UnInitializeSimulationHandler()
  {
    if (this.m_simulationHandler == null)
      return;
    this.m_simulationHandler.UnInitialize();
    this.UnRegisterForSimulationHandlerEvents();
    this.m_simulationHandler = (CApObjectSweptVolumeSimulationHandler) null;
  }

  private void RegisterForSimulationHandlerEvents()
  {
    this.m_simulationHandler.simulationEventOccurred += new CApObjectSweptVolumeSimulationHandler.SimulationEventHandler(this.M_simulationHandler_simulationEventOccurred);
  }

  private void UnRegisterForSimulationHandlerEvents()
  {
    this.m_simulationHandler.simulationEventOccurred -= new CApObjectSweptVolumeSimulationHandler.SimulationEventHandler(this.M_simulationHandler_simulationEventOccurred);
  }

  private void M_simulationHandler_simulationEventOccurred(
    object sender,
    CApObjectSweptVolumeSimulationHandler.SimulationEventArgs args)
  {
    switch (args.EventType)
    {
      case CApObjectSweptVolumeSimulationHandler.eSimulationEventType.Started:
        if (this.m_simulationHandler != null && !this.m_simulationHandler.IsSilentSimulation && this.m_simulationHandler.CurrentSimulationTime == 0.0)
          this.ClearCollectedData();
        this.IsSimulationRunning = true;
        break;
      case CApObjectSweptVolumeSimulationHandler.eSimulationEventType.Stopped:
        this.IsSimulationRunning = false;
        break;
    }
  }

  private bool MayProceedCalculation(int progress)
  {
    if (progress >= 0 && progress <= 100 && (double) progress > this.Progress)
      this.Progress = (double) progress;
    Application.DoEvents();
    return this.m_sweptVolumeCreator != null && !this.m_sweptVolumeCreator.ShouldAbort;
  }

  public class ItemSelectionForcedEventArgs
  {
    public readonly IEnumerable<int> Rows;

    public ItemSelectionForcedEventArgs(IEnumerable<int> rows) => this.Rows = rows;
  }

  public delegate void ItemSelectionForcedEventHandler(
    object sender,
    CObjectSweptVolumeViewModel.ItemSelectionForcedEventArgs e);
}
